package com.zhouchao.gateway.filter;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: zhouchao
 * @Date: 2021/10/14 23:11
 * @Description:
 */
@Slf4j
@RefreshScope
@Component
public class CurrentLimitingFilter implements GlobalFilter, Ordered {

    @Value("${LIMIT_TIME}")
    private Integer LIMIT_TIME;

    @Value("${LIMIT_COUNT}")
    private Integer LIMIT_COUNT;

    /**
     * 缓存的请求
     */
    private static Cache<String, AtomicInteger> requestCache;

    @PostConstruct
    public void init(){
        requestCache = CacheBuilder.newBuilder()
                .expireAfterAccess(LIMIT_TIME, TimeUnit.MINUTES)
                .maximumSize(Integer.MAX_VALUE)
                .build();
    }



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();
        ConcurrentMap<String, AtomicInteger> concurrentMap = requestCache.asMap();
        AtomicInteger atomicInteger = concurrentMap.get(clientIp);
        //这里的数据不敏感，为了性能，所以就不加锁了
        if (atomicInteger == null) {
            atomicInteger = new AtomicInteger();
            requestCache.put(clientIp,atomicInteger);
        }
        int count = atomicInteger.incrementAndGet();
        if (count > LIMIT_COUNT){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            log.debug("IP:" +clientIp +",频繁访问，被拒绝");
            String data = "The server that accessed too frequently refused the request";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}